/**
 * 遍历数组并执行回调函数
 * @param arr 数组
 * @param fn 回调函数
 */
export const forEach = <T>(arr: T[], fn: (item: T, index: number, array: T[]) => void): void => {
  if (!arr.length || !fn) return
  const i = -1
  const len = arr.length
  while (++i < len) {
    const item = arr[i]
    fn(item, i, arr)
  }
}

/**
 * 得到两个数组的交集，两个数组的元素为数值或字符串
 * @param arr1 数组1
 * @param arr2 数组2
 * @returns 交集数组
 */
export const getIntersection = <T>(arr1: T[], arr2: T[]): T[] => {
  const len = Math.min(arr1.length, arr2.length)
  const i = -1
  const res: T[] = []
  while (++i < len) {
    const item = arr2[i]
    if (arr1.indexOf(item) > -1) res.push(item)
  }
  return res
}

/**
 * 得到两个数组的并集，两个数组的元素为数值或字符串
 * @param arr1 数组1
 * @param arr2 数组2
 * @returns 并集数组
 */
export const getUnion = <T>(arr1: T[], arr2: T[]): T[] => {
  return Array.from(new Set([...arr1, ...arr2]))
}

/**
 * 判断要查询的数组是否至少有一个元素包含在目标数组中
 * @param targetArr 目标数组
 * @param arr 查询数组
 * @returns 是否包含
 */
export const hasOneOf = <T>(targetArr: T[], arr: T[]): boolean => {
  return targetArr.some((_) => arr.indexOf(_) > -1)
}

/**
 * 判断值是否在有效列表中
 * @param value 要验证的值
 * @param validList 有效列表
 * @returns 是否在列表中
 */
export const oneOf = <T>(value: T, validList: T[]): boolean => {
  for (const i = 0; i < validList.length; i++) {
    if (value === validList[i]) {
      return true
    }
  }
  return false
}

/**
 * 判断时间戳格式是否是毫秒
 * @param timeStamp 时间戳
 * @returns 是否是毫秒
 */
const isMillisecond = (timeStamp: number): boolean => {
  const timeStr = String(timeStamp)
  return timeStr.length > 10
}

/**
 * 判断传入的时间戳是否早于当前时间戳
 * @param timeStamp 传入的时间戳
 * @param currentTime 当前时间时间戳
 * @returns 是否早于
 */
const isEarly = (timeStamp: number, currentTime: number): boolean => {
  return timeStamp < currentTime
}

/**
 * 如果传入的数值小于10，即位数只有1位，则在前面补充0
 * @param num 数值
 * @returns 处理后的字符串
 */
const getHandledValue = (num: number): string => {
  return num < 10 ? '0' + num : num.toString()
}

/**
 * 根据时间戳和格式类型返回时间字符串
 * @param timeStamp 时间戳
 * @param startType 格式类型
 * @returns 时间字符串
 */
const getDate = (timeStamp: number, startType?: string): string => {
  const d = new Date(timeStamp * 1000)
  const year = d.getFullYear()
  const month = getHandledValue(d.getMonth() + 1)
  const date = getHandledValue(d.getDate())
  const hours = getHandledValue(d.getHours())
  const minutes = getHandledValue(d.getMinutes())
  const second = getHandledValue(d.getSeconds())
  const resStr = ''
  if (startType === 'year')
    resStr = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second
  else resStr = month + '-' + date + ' ' + hours + ':' + minutes
  return resStr
}

/**
 * 获取相对时间字符串
 * @param timeStamp 时间戳
 * @returns 相对时间字符串
 */
export const getRelativeTime = (timeStamp: number): string => {
  const IS_MILLISECOND = isMillisecond(timeStamp)
  if (IS_MILLISECOND) Math.floor((timeStamp /= 1000))
  timeStamp = Number(timeStamp)
  const currentTime = Math.floor(Date.parse(new Date()) / 1000)
  const IS_EARLY = isEarly(timeStamp, currentTime)
  const diff = currentTime - timeStamp
  if (!IS_EARLY) diff = -diff
  const resStr = ''
  const dirStr = IS_EARLY ? '前' : '后'
  if (diff <= 59) resStr = diff + '秒' + dirStr
  else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + '分钟' + dirStr
  else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + '小时' + dirStr
  else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + '天' + dirStr
  else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp)
  else resStr = getDate(timeStamp, 'year')
  return resStr
}

/**
 * 获取当前浏览器名称
 * @returns 浏览器名称
 */
export const getExplorer = (): string => {
  const ua = window.navigator.userAgent
  const isExplorer = (exp: string): boolean => {
    return ua.indexOf(exp) > -1
  }
  if (isExplorer('MSIE')) return 'IE'
  else if (isExplorer('Firefox')) return 'Firefox'
  else if (isExplorer('Chrome')) return 'Chrome'
  else if (isExplorer('Opera')) return 'Opera'
  else if (isExplorer('Safari')) return 'Safari'
  return 'Unknown'
}

/**
 * 绑定事件
 * @param element 元素
 * @param event 事件名
 * @param handler 事件处理函数
 */
export const on = (function () {
  if (document.addEventListener) {
    return function (
      element: HTMLElement | Document,
      event: string,
      handler: EventListenerOrEventListenerObject
    ): void {
      if (element && event && handler) {
        element.addEventListener(event, handler, false)
      }
    }
  } else {
    return function (
      element: HTMLElement | Document,
      event: string,
      handler: EventListenerOrEventListenerObject
    ): void {
      if (element && event && handler) {
        ;(element as any).attachEvent('on' + event, handler)
      }
    }
  }
})()

/**
 * 解绑事件
 * @param element 元素
 * @param event 事件名
 * @param handler 事件处理函数
 */
export const off = (function () {
  if (document.removeEventListener) {
    return function (
      element: HTMLElement | Document,
      event: string,
      handler: EventListenerOrEventListenerObject
    ): void {
      if (element && event) {
        element.removeEventListener(event, handler, false)
      }
    }
  } else {
    return function (
      element: HTMLElement | Document,
      event: string,
      handler: EventListenerOrEventListenerObject
    ): void {
      if (element && event) {
        ;(element as any).detachEvent('on' + event, handler)
      }
    }
  }
})()

/**
 * 判断一个对象是否存在key，如果传入第二个参数key，则是判断这个obj对象是否存在key这个属性
 * 如果没有传入key这个参数，则判断obj对象是否有键值对
 * @param obj 对象
 * @param key 键
 * @returns 是否存在
 */
export const hasKey = <T>(obj: T, key?: keyof T): boolean => {
  if (key) return key in obj
  else {
    const keysArr = Object.keys(obj)
    return keysArr.length > 0
  }
}

/**
 * 判断两个对象是否相等，这两个对象的值只能是数字或字符串
 * @param obj1 对象1
 * @param obj2 对象2
 * @returns 是否相等
 */
export const objEqual = <T extends Record<string, any>>(obj1: T, obj2: T): boolean => {
  const keysArr1 = Object.keys(obj1)
  const keysArr2 = Object.keys(obj2)
  if (keysArr1.length !== keysArr2.length) return false
  else if (keysArr1.length === 0 && keysArr2.length === 0) return true
  else return !keysArr1.some((key) => obj1[key] != obj2[key])
}
